#include "CalendarStructure.h"


DayCell::DayCell()
{
   td_line = 0;
   tr_line = 0;
	 modus = 0;
	 data = QByteArray("</error>");
}


QIcon DayCell::createColorToolButtonIcon( int setmodus )
    {
    QPixmap pixmap(50, 50);
    pixmap.fill(BG(setmodus));
    QPainter painter(&pixmap);
    return QIcon(pixmap);
}


QPixmap DayCell::NoteIcon()
{
    QPixmap pixmap(28,2);
    pixmap.fill(Qt::darkBlue);
    QPainter painter(&pixmap);
    return pixmap;
}

    
DayCell DayCell::operator=( const DayCell d )
{
      //////qDebug() << "operator = DayCell->" << d.note.size();
	
      td_line = d.td_line;
      tr_line = d.tr_line;
      modus = d.modus;
      dax = d.dax;
      note = d.note;
      data = d.data;
      return *this;
}

/*
bool DayCell::operator==( const DayCell &d ) const
{
           if (td_line == d.td_line && 
               tr_line == d.tr_line && 
     dax.toJulianDay() == d.dax.toJulianDay() ) {
      return true;
     } else {
      return false;
     }
 
}

*/


void DayCell::Register( int tr , int td , const QDate d , int gyear ,  int mod )
{
   td_line = td;
   tr_line = tr;
	 modus = mod;
   dax = d;
	 anno = gyear;
}

bool DayCell::isValid()
{
       if (modus !=0 || note.size() !=0) {
         return true;
       } else {
         return false;
       }
}


QColor DayCell::BG( int setmodus ) 
    {
         /* reservation modus    0= libero / 1= prenotato / 2= prenotato provvisorio / 3= riservato / 10 = chiuso / */
      
         if ( setmodus == 1 ) {
					 return QColor("#ffb4a7");
				 } else if ( setmodus == 2 ) {
					 return QColor("#ffcf97");
				 } else if ( setmodus == 3 ) {
					 return QColor("#ff0000");
				 } else if ( setmodus == 10 ) {
					 return QColor("#bfbfbf");
				 } else {
           return QColor(Qt::white);
         }
}

QColor DayCell::FC( int setmodus ) 
{
      /* reservation modus    0= libero / 1= prenotato / 2= prenotato provvisorio / 3= riservato / 10 = chiuso / */
      
         if ( setmodus == 1 ) {
					 return QColor(Qt::white);
				 } else if ( setmodus == 2 ) {
					 return QColor(Qt::white);
				 } else if ( setmodus == 3 ) {
					 return QColor(Qt::white);
				 } else if ( setmodus == 10 ) {
					 return QColor(Qt::white);
				 } else {
           return QColor(Qt::darkBlue);
         }
}

int DayCell::fromUday()
{
   QDate unixtime = QDate(1970,1,1);
	 return dax.toJulianDay()  -  unixtime.toJulianDay();
}

CalendarItem *DayCell::on_Table()
{
	 int Weekday = dax.dayOfWeek();
	 QString debugplay;//////////// = QString("<br/><br/>Debug modus = %1").arg(modus);
	 QString base = QString("%1< ID:%2 %3").arg(dax.toString()).arg(fromUday()).arg(debugplay);
	 int mcheck = tr_line + 1;
	 CalendarItem *item = new CalendarItem(dax);
	 item->setTextAlignment ( Qt::AlignVCenter | Qt::AlignHCenter );
	 QTextDocument doc;
	
	          doc.setHtml("<p><b>" + base + "</b><p>");
             doc.setTextWidth(350);
	           item->setToolTip(doc.toHtml()); 
	
	 if (dax.month() != mcheck) {
		  item->setData (Qt::ForegroundRole ,QColor("#e6e6e6")) ;
	    item->setData (Qt::BackgroundColorRole ,QColor("#e6e6e6"));
		  item->setFlags ( Qt::ItemIsTristate );
	    item->setData(Qt::DecorationRole,QVariant());
	    item->setData(Qt::SizeHintRole,sizeHint());
		  item->setToolTip(""); 
		  return item;
	 }
	 
	 
			 if (note.size() > 0) {
				doc.setHtml( "<b>" + base + "</b><br/><h2>" + note.at(0) +"</h2>");
				 doc.setTextWidth(350);
				 const QString Dimme = note.first();
				qDebug() << "#### Dimme  " << note.size();
				qDebug() << "#### Dimme  " << note.join("/");
				 item->Tipe(Dimme); 
				 ///////item->setStatusTip(QString("%1").arg(Dimme)); 
			 item->setData(Qt::DecorationRole,NoteIcon());
			 //////item->setToolTip("Open on reader application."); 
				 
			 } else {
				 item->setData(Qt::DecorationRole,QVariant());
			 }
			 
			 item->setFlags ( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
	 
	 if (modus == 0 ) {
		       if (note.size() < 1) {
					 item->setData(Qt::DecorationRole,QVariant());
					 }
					 
		       if (Weekday == 7) {
					 item->setData (Qt::BackgroundColorRole ,QBrush(QColor("#d2d5ff"),Qt::Dense5Pattern));
					 item->setData (Qt::ForegroundRole ,QColor(Qt::darkBlue)) ;
					 } else {
					 item->setData (Qt::BackgroundColorRole ,QColor(Qt::white));
		       item->setData (Qt::ForegroundRole ,QColor(Qt::darkBlue)) ;
					 }
					 
					  if (dax == QDate::currentDate() && mcheck == dax.month() ) {
		        item->setData (Qt::BackgroundColorRole ,QColor("#ffd267"));
		        item->setData (Qt::ForegroundRole ,QColor("#000000")) ;
	          }
		return item;
	 }
	 /* only modus !=0 */
	 item->setData (Qt::BackgroundColorRole ,QBrush(BG(modus )));
   item->setData (Qt::ForegroundRole ,FC(modus) );
	return item;
}

void DayCell::Fill_Html_Cell( QTextTableCell hcell , bool outday )  /* true on valid date */
{
	 QTextCursor cur = hcell.firstCursorPosition();
	
	 QFont fo = qApp->font();
	 QFont fob = qApp->font();
	 fo.setPointSizeF(5.9);
	 fob.setPointSizeF(5.9);
	 fob.setKerning ( true );
	 fo.setKerning ( true );
	 fob.setBold(true);
	 QStringList RTFmonth = QStringList() << " " << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
	 int coolnr = hcell.column(); 
	 int mcheck = tr_line + 1;
	 
	 QString txt;
	 if (coolnr == 0 ) {
		 modus = 0;
		 txt = RTFmonth.at(hcell.row());
	 } else {
		 txt = text();
	 }
	 
	  QDate first(dax.year(),mcheck,1);   /* first day periode */
    QDateTime day_1(first);   /* range start */
    QDateTime day_last = day_1.addMonths(1);  /* range stop */
    const int lastday = day_last.date().day();
	  QDate Ulast = day_last.date();
	 
	  QString strm = QString::number(mcheck);
	 
	 
	 int Weekday = dax.dayOfWeek();
	 
	 QTextCharFormat existformat = hcell.format();
	 existformat.setFont(fo);
	 QTextBlockFormat para;
	 para.setAlignment ( Qt::AlignHCenter  ); 
	 QTextCharFormat Inline = existformat;
	 Inline.setVerticalAlignment ( QTextCharFormat::AlignTop );
	 Inline.setForeground(QColor(Qt::darkBlue));
	 /* non nel mese !! */
	 if ( dax < first ) {
		     existformat.setBackground(QColor("#ffffff"));
		     Inline.setForeground(QColor("#ffffff"));
				 hcell.setFormat(existformat);
				 cur.setBlockFormat ( para );
				 cur.beginEditBlock();
				 cur.insertText(".",Inline);
				 cur.endEditBlock();
		     return;
	 }
	 if ( dax > Ulast ) {
		     existformat.setBackground(QColor("#ffffff"));
		     Inline.setForeground(QColor("#ffffff"));
				 hcell.setFormat(existformat);
				 cur.setBlockFormat ( para );
				 cur.beginEditBlock();
				 cur.insertText(".",Inline);
				 cur.endEditBlock();
		     return;
	 }
	 Inline.setVerticalAlignment ( QTextCharFormat::AlignTop );
	 Inline.setForeground(QColor(Qt::darkBlue));
	 
	 if (!alternate_text.isEmpty()) {
	       Inline.setFont(fob);
	       existformat.setBackground(QColor("#40578f"));
				 para.setForeground(QColor("#ffffff"));
				 Inline.setForeground(QColor("#ffffff"));
		     hcell.setFormat(existformat);
				 cur.setBlockFormat ( para );
				 cur.beginEditBlock();
				 cur.insertText(alternate_text,Inline);
				 cur.endEditBlock();
		     return;
		}
	 
	 if (modus == 0 ) {
		     if (Weekday == 7) {
         existformat.setBackground(QColor("#d2d5ff"));
				 Inline.setFont(fob);
				 Inline.setForeground(QColor("#ffffff"));
				 } else {
				 existformat.setBackground(QColor("#ffffff")); 
				 Inline.setFont(fo);
				 }
				 
				 
				 
				 
				 hcell.setFormat(existformat);
				 cur.setBlockFormat ( para );
				 cur.beginEditBlock();
				 cur.insertText(txt,Inline);
				 cur.endEditBlock();
		     return;
	 } else {
		 
	 /* only modus !=0 */
				 existformat.setBackground(BG(modus)); 
				 Inline.setFont(fob);
				 Inline.setForeground(FC(modus));  
				 ///////Inline.setToolTip(QString("Modus %1").arg(modus));
				 hcell.setFormat(existformat);
				 cur.setBlockFormat ( para );
				 cur.beginEditBlock();
				 cur.insertText(txt,Inline);
				 cur.endEditBlock();
	       return;
		 
		 
	 }

}

QString DayCell::text() 
{
	if (!alternate_text.isEmpty()) {
	return alternate_text;
	}
	return QString("%1").arg(dax.toString("dd"));
}

int DayCell::day()
{
	return dax.day();
}

int DayCell::year()
{
	return dax.year();
}





QDataStream& operator<<(QDataStream& out, const DayCell& udoc)
{
    out << udoc.td_line;
    out << udoc.tr_line;
    out << udoc.modus;
	  out << udoc.anno;
    out << udoc.dax;
    out << udoc.data;
    out << udoc.note;
    return out;
}

QDataStream& operator>>(QDataStream& in, DayCell& udoc)
{
   in >> udoc.td_line;
   in >> udoc.tr_line;
   in >> udoc.modus;
	 in >> udoc.anno;
   in >> udoc.dax;
   in >> udoc.data;
   in >> udoc.note;
  return in;
}

TableCalendar::TableCalendar()
{
 anno_min = 0;
 anno_max = 0;
 owner = 0;
 lastupdate = QDateTime::currentDateTime();
}

QString TableCalendar::name_m( int m )
{
   QStringList RTFmonth = QStringList() << "NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
   return RTFmonth.at(m);
}


QPixmap TableCalendar::image_year( int y )  
{
			    QTextDocument *doc = new QTextDocument();
				QString htmldata = html_year(y);
                doc->setHtml(htmldata);
				QTextFrame  *Tframe = doc->rootFrame();
				QTextFrameFormat rootformats = Tframe->frameFormat();
				rootformats.setBottomMargin (0); 
				rootformats.setTopMargin(0); 
				rootformats.setRightMargin (0); 
				rootformats.setLeftMargin (0); 
				rootformats.setPadding (0); 
				doc->adjustSize();
                Tframe->setFrameFormat ( rootformats );
				QPixmap PicsDocument(doc->idealWidth(),190);
				PicsDocument.fill(Qt::white);
				QRectF clip(0, 0,PicsDocument.width(),PicsDocument.height());
				QPainter *p = new QPainter(&PicsDocument);
                p->setRenderHint(QPainter::Antialiasing, true);
                doc->drawContents(p,clip);
				p->end();
				return PicsDocument;
}




QString TableCalendar::html_year( int y )  
{
	  const int Anno = y;
	  int validday = 0;
	  ////////TableCalendar Xhtml;
		////////Xhtml.InitRange(Anno - 1,Anno + 1,0); 
	  ////QMap<int,DayCell> Worker = taco.Works();
	  //////////Xhtml.MemoDay = taco.Works();
	  int CursorPointer = 0;
	  int linee = 13;
		int scritte_linee = linee - 1;
	  int colonne = 1 + LunghezzaMassimaRighe(y);
    QTextDocument *doc = new QTextDocument();
	  QTextFrame  *Tframe = doc->rootFrame();
	  QTextFrameFormat rootformats = Tframe->frameFormat();
    rootformats.setBottomMargin (0); 
    rootformats.setTopMargin(0); 
    rootformats.setRightMargin (0); 
    rootformats.setLeftMargin (0); 
    rootformats.setPadding (0); 
    rootformats.setWidth(800); 
    Tframe->setFrameFormat ( rootformats );
    QTextCursor Tcursor = QTextCursor(doc);
		QTextTable *qtable = Tcursor.insertTable(linee,colonne);  /////// righe##############################
	  //////////////////// ##############table define #####################################################
    QTextTableFormat tableFormat; /////// = qtable->format();
	  tableFormat.setWidth ( QTextLength ( QTextLength::PercentageLength,100)  );
	
	     QVector<QTextLength> constraints;
        for (int i = 0; i < colonne; ++i) {
					constraints.insert(i,QTextLength(QTextLength::PercentageLength,2.77777)); 
        }
	  tableFormat.setColumnWidthConstraints ( constraints ); 
    tableFormat.setBackground ( QColor("#40578f") );
    tableFormat.setBorder(0);
    tableFormat.setCellSpacing(1);
    tableFormat.setCellPadding(1);
    tableFormat.setAlignment ( Qt::AlignLeft );
	  QStringList RTFdays = QStringList() << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
		QStringList testa;
		testa.clear();
		int dax = 0;
		for (int i=0; i<50; i++) {
			if (i==0) {
				dax--;
			testa.append(" ");
			} else {
			testa.append(RTFdays.at(dax));
			}
			dax++;
			if (dax == 7) {
			dax = 0;
			}
	  }
	  for (int e = 0; e < colonne; ++e) {
			                      DayCell header;
			                      header.modus = 0; 
                            header.alternate_text = testa.at(e);		
			                      QTextTableCell cellheader = qtable->cellAt(0,e);
			                      header.Fill_Html_Cell(cellheader,true);
		}
		for (int i = 0; i < scritte_linee; ++i) {
			
			                      DayCell dummy;
			                      dummy.modus = 0; 
			                      dummy.alternate_text = name_m(i+1);
			
			const int mesex = i + 1;
			
											 QList<DayCell> li = Take(Anno,i);			
			
			                 for (int o = 0; o < colonne; ++o) {
												 QTextTableCell cellstart = qtable->cellAt(i+1,o);
												 if (o == 0) {
													 dummy.Fill_Html_Cell(cellstart,true);
												 } else {
													 DayCell pin = li[o-1];
													         if (isMemo( pin.fromUday() )) {
																		   DayCell oldpi = MemoDay.value(pin.fromUday());
																		    if (oldpi.dax.month() !=mesex) {
																					pin.Fill_Html_Cell(cellstart);
																				} else {
																					pin.modus = oldpi.modus;
																		      pin.Fill_Html_Cell(cellstart);
																				}
																		 
																		   validday++;
																	 } else {
																		 pin.Fill_Html_Cell(cellstart);
																	 }
													 
												 }
											 }
			
			
		}
	
	  qtable->setFormat( tableFormat );
		doc->adjustSize();
		/*
		qreal wi = doc->idealWidth();
		qreal hi = doc->size().rheight();
		
		    QRect Rdimension(0,0,wi,hi);
        QPixmap PicsDocument(Rdimension.size());
        PicsDocument.fill(Qt::transparent);
        QPainter *p = new QPainter(&PicsDocument);
        p->setRenderHint(QPainter::Antialiasing, true);
        doc->drawContents(p,Rdimension);
		    QPixmap Pix = PicsDocument.scaledToWidth(550,Qt::SmoothTransformation); 
		    Pix.save("ssss.png","PNG",100);
		*/
		QString errorStr;
    int errorLine, errorColumn;
    QDomDocument exdoc;
    if (!exdoc.setContent(doc->toHtml("utf-8"),false, &errorStr, &errorLine, &errorColumn)) {
        return QString();
    }
		QDomElement root = exdoc.documentElement();
    QDomNode child;
    QDomElement e = root.firstChildElement("body");
		
		QDomDocument doc2;
		QDomElement roo = doc2.createElement("var");
		doc2.appendChild(roo);
		if (validday < 1) {
			return doc2.toString(5);
		}
    QDomElement blox = doc2.createElement("div");
                blox.setAttribute ("id",QString("calendar_%1").arg(Anno));
		            blox.setAttribute ("xmlns","http://www.w3.org/1999/xhtml");
    roo.appendChild(blox);
		
		   child = e.firstChild();
       while ( !child.isNull() ) {
           if ( child.isElement() ) {
            blox.appendChild(doc2.importNode(child,true).toElement());
           } else if (child.isText()) {
             blox.appendChild(doc2.createTextNode(child.toText().data()));
           }
         child = child.nextSibling();            
       }
		
		
		return doc2.toString(5);
}
		 
int TableCalendar::LunghezzaMassimaRighe( int anno )
{
	    const int RIGHE_MESE = 42;
	    QList<QDate> daytemp;
	    daytemp.clear();
	    int daymesemax = 0;
	
		 for (int Monthis = 1; Monthis <= 12; ++Monthis) {
          const int mese =  Monthis;
			    QDate first(anno,mese,1);  /* primo giorno */
			    QDateTime day_1(first);
			    QDateTime day_last = day_1.addMonths(1);
					int TotalDays = day_1.daysTo(day_last);
			 
			    int nrappend = 0;
			      if (first.dayOfWeek() !=1) {
            nrappend = first.dayOfWeek() - 1;  /* 1 - 6 */
            }
						
			    for (int dd = 1; dd <= TotalDays; ++dd) {
						const int colonna = nrappend + dd;
            daymesemax = qMax(colonna,daymesemax); 
					}
     }
	return daymesemax;
	
}
	 

void TableCalendar::AppendMonth( int y, int m )
  {
    const int row_line = m - 1;    /* cool size - 1 */
		const int RIGHE_MESE = 42;
    const int NextYear = y + 1;
    QDate first(y,m,1);   /* first day periode */
    QDate next_Y(NextYear,1,1);  /* if M december  append here day */
    const int WeekfirstM = first.dayOfWeek() - 1;
    QDateTime day_1(first);   /* range start */
    QDateTime day_last = day_1.addMonths(1);  /* range stop */
    const int WeeklastM = day_last.date().dayOfWeek();
    int TotalDays = day_1.daysTo(day_last);
    ram_day.clear();
		QStringList debug_visual;
		            debug_visual.append(name_m(m)+QString("/%1").arg(y));
    int append = -1;
    /////////qDebug() << "################################################ ";
    /////////qDebug() << "start........ " << name_m(m);
   
            if (first.dayOfWeek() !=1) {
            append = first.dayOfWeek() - 1;  /* 1 - 6 */
            const int prepend_sum = append;
                      while (ram_day.size() < prepend_sum)
                      {
                         ram_day.append(day_1.addDays(0 - append).date());
                         append--;
                      }                       
             
            } else {
            append = 0;
            }
					
            /* normal */
            for (int dd = 1; dd <= TotalDays; ++dd) {
             QDate sopra(y,m,dd);
             ram_day.append(sopra);
            }
            append = -1;
             while (ram_day.size() < RIGHE_MESE)
             {
                append++;
                 if (m == 12) {
                  QDateTime newYears = QDateTime(next_Y); 
                  ram_day.append(newYears.addDays(append).date());
                  ////////qDebug() << " nuovo anno   " << m << " " << newYears.date().year();
                 } else {
                   ram_day.append(day_last.addDays(append).date());
                 }
              
             }
             append = -1;
             for (int i=0; i<RIGHE_MESE; i++) {
               QDate realdate = ram_day[i];
							   DayCell prepare;
							           prepare.Register(m - 1,i,realdate,y,0);
                         ///////qDebug() << " day line ->" << i << " d." << realdate;
							           visual_day.append(prepare);
							           debug_visual << QString("%1").arg(realdate.day());
							           append++;
              }
							///////qDebug() << "#### " << debug_visual.join(",");
							///////
							///////qDebug() << "#### check real 35 " << append + 1;
              ram_day.clear();    
       ////////////qDebug() << "################################################ ";
   
  }





void TableCalendar::AppendYear( int y )
{
     for (int Monthis = 1; Monthis <= 12; ++Monthis) {
           AppendMonth(y,Monthis);
     }
}


QList<DayCell> TableCalendar::Take( int y  )
{
   QList<DayCell> li;
	   for (int i=0; i<visual_day.size(); i++) {
			   DayCell pin = visual_day[i];
			   if (pin.anno == y) {
					 li.append(pin);
				 }
		 }
	 return li;
}

QList<DayCell> TableCalendar::Take( int y  , int line )
{
   QList<DayCell> li;
	   for (int i=0; i<visual_day.size(); i++) {
			   DayCell pin = visual_day[i];
			   if (pin.anno == y && pin.tr_line == line) {
					 li.append(pin);
				 }
		 }
	 return li;
}

DayCell TableCalendar::TakeItem( int epoca )
{
	   for (int i=0; i<visual_day.size(); i++) {
			   DayCell pin = visual_day[i];
			   if (pin.fromUday() == epoca) {
					 return pin;
				 }
		 }
		 DayCell dummy;
	 return dummy;
}




void TableCalendar::InitRange( int mi ,  int max , const int user )
{
   anno_min = qMin(mi,max);
   anno_max = qMax(mi,max);
   lastupdate = QDateTime::currentDateTime();
   owner = user;
   visual_day.clear();
     for (int Years = anno_min; Years <= anno_max; ++Years) {
           AppendYear(Years);
     }
}

QString TableCalendar::Html_build()
{
	if (memo_size() < 1) {
		return QString();
	}
	
	  QDomDocument anni;
    QDomProcessingInstruction header = anni.createProcessingInstruction( "xml", "version=\"1.0\" " );
    anni.appendChild( header );
    QDomElement root = anni.createElement("root");
	  root.setAttribute ("owner",owner);
    anni.appendChild( root );
	  QDomNode child;
	  QString errorStr;
    int errorLine, errorColumn;
	
	  QDate now = QDate::currentDate();
	
	bool destroi = false;
	if (visual_day.size() < 1) {
		  visual_day.clear();
		  destroi = true;
		        
						const int AYear = now.year();
						anno_max = AYear + 8;
						anno_min = AYear - 3;
						InitRange(anno_min,anno_max,owner);
		 
	} else {
		
		
		
	}
	   const int starter = now.year();
	   const int stoper = starter + 1;
	
	   for (int Years = starter; Years <= stoper; ++Years) {
                    QString pane = html_year( Years );
							      QDomElement unanno = anni.createElement("years");
							                  unanno.setAttribute ("year",Years);
			                   
										QDomDocument exdoc;
										if (!exdoc.setContent(pane,false, &errorStr, &errorLine, &errorColumn)) {
											  if (destroi) {
													visual_day.clear();
												}
												return QString();
										} else {
											QDomElement e = exdoc.documentElement();
											child = e.firstChild();
															 while ( !child.isNull() ) {
																	 if ( child.isElement() ) {
																		 unanno.appendChild(anni.importNode(child,true).toElement());
																	 } else if (child.isText()) {
																		 unanno.appendChild(anni.createTextNode(child.toText().data()));
																	 }
																 child = child.nextSibling();            
															 }
											  root.appendChild( unanno );
										}
             }
						 
					if (destroi) {
					visual_day.clear();
					}	 
					
			QPixmap towebs = image_year(now.year());
			QByteArray bytes;
      QBuffer buffer(&bytes);
      buffer.open(QIODevice::WriteOnly);
      towebs.save(&buffer,"PNG");
			web = bytes.toBase64();
			return anni.toString(5);
}






Calendar::Calendar( int user , QWidget *parent  )
 : QTableWidget(12,42,parent)
{
  ////////QStringList RTFdays = QStringList() << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
	QStringList RTFdays = QStringList() << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
	QStringList testa;
	testa.clear();
	int dax = 0;
	for (int i=0; i<model()->columnCount(); i++) {
		testa.append(RTFdays.at(dax));
		dax++;
		if (dax == 7) {
		dax = 0;
		}
	}
	
  setMinimumSize (600,310);
	QStringList RTFmonth = QStringList() << "Gen" << "Feb" << "Mar" << "Apr" << "Mag" << "Giu" << "Lug" << "Ago" << "Set" << "Ott" << "Nov" << "Dic";
	setVerticalHeaderLabels(RTFmonth); 
	setHorizontalHeaderLabels(testa);
	setContextMenuPolicy(Qt::DefaultContextMenu);
	init(user);
	setItemDelegate(new CustomDelegate());
	emit Range(MinY,MaxY,ActiveYear);
}

void Calendar::init( int user )
{
	
	QDate now = QDate::currentDate();
	ActiveYear = now.year();
	MaxY = ActiveYear + 8;
  MinY = ActiveYear - 3;
  taco.InitRange(MinY,MaxY,user); 
	colonnemassimo = taco.LunghezzaMassimaRighe(ActiveYear);
	PlayYear(ActiveYear);
	resizeColumnsToContents();
	resizeRowsToContents();
	
}


bool Calendar::HavingYear( int y )
{
	for (int Years = MinY; Years <= MaxY; ++Years) {
		if (Years == y) {
			return true;
		}
	}
	return false;
}


void Calendar::SwapYear()
{
	QAction *invoice = qobject_cast<QAction *>(sender());
	int gotoY = invoice->data().toInt();
	if (!HavingYear( gotoY )) {
	return;
	}
	PlayYear(gotoY);
	
}

void Calendar::PlayYear( const int InYear)
{
	ActiveYear = InYear;
	setWindowTitle (QString("Anno %1 / Oggetto %2 / Ultimo aggiornamento %3").arg(ActiveYear).arg(taco.owner).arg(taco.lastupdate.toString())); 
	colonnemassimo = taco.LunghezzaMassimaRighe(ActiveYear);
	for (int ri = 0; ri <= model()->columnCount(); ++ri) {
		showColumn(ri);
	}
	for (int ci = colonnemassimo; ci <= model()->columnCount(); ++ci) {
		hideColumn(ci);
	}
	resizeColumnsToContents();
	resizeRowsToContents();
	
	////////qDebug() << "### colonnemassimo  " << colonnemassimo;  //////////  && pin.dax.month() == mesex 
	CalendarItem *Cell;
	
	    for (int line = 0; line <= 11; ++line) {
							QList<DayCell> li = taco.Take(ActiveYear,line);
							           for (int x=0; x<li.size(); x++) {
			                        DayCell pin = li[x];
													    const int mesex = line + 1;
													    if (taco.isMemo( pin.fromUday() )) {
																   
																   DayCell oldpi = taco.MemoDay.value(pin.fromUday());
																   if (oldpi.dax.month() == mesex) {
																			pin.note = oldpi.note;
																			pin.modus = oldpi.modus;
																		  qDebug() << "trovato  " << pin.fromUday() << "-" << mesex << "-" << oldpi.dax.month();
																	 }
																   
															}
													    Cell = pin.on_Table();
															Cell->setData(Qt::UserRole,pin);
													    setItem(line,x,Cell);   ///////////DayCell TableCalendar::isMemo( const DayCell d  ) 
												 }
						}
						
	       resizeColumnsToContents();
	       resizeRowsToContents();
		clearSelection();
		emit Range(MinY,MaxY,ActiveYear);
}

void Calendar::Riservati()
{
	QAction *invoice = qobject_cast<QAction *>(sender());
	int ModusMake = invoice->data().toInt();
	
	
  QList<QTableWidgetItem *> selezioni = selectedItems();
	
	
	if (selezioni.size() < 0) {
		QMessageBox::warning(0, tr("Error Calendar!"),tr("No Selection state found!"));
		return;
	} else {

					for (int i=0; i<selezioni.size(); i++) {
						DayCell fday = selezioni[i]->data(Qt::UserRole).value<DayCell>();
						                  fday.modus = ModusMake;
						                  if (ModusMake == 0) {
																fday.note.clear();
															}
						                  CalendarItem *Cell = fday.on_Table();
													    Cell->setData(Qt::UserRole,fday);
													    setItem(fday.tr_line,fday.td_line,Cell);
						                  taco.MemoDay.insert(fday.fromUday(),fday);  /* insert or replace memo !!!! */
					}
	}
	clearSelection();
	taco.lastupdate = QDateTime::currentDateTime();
	
}


void Calendar::Notaday()
{
	
  QList<QTableWidgetItem *> selezioni = selectedItems();
	QString notatxt;
	
	if (selezioni.size() < 0) {
		QMessageBox::warning(0, tr("Error Calendar!"),tr("No Selection state found!"));
		return;
	} else {
		
		      QTableWidgetItem *one = selezioni.first();
					DayCell pday = one->data(Qt::UserRole).value<DayCell>();  
		      QString enote;
		      if (pday.note.size() > 0) {
						enote = pday.note.at(0);
					}

		     notatxt = QInputDialog::getText(this, tr("La vostra nota (Mass. 110 char.)"),tr("Nota:"), QLineEdit::Normal,enote);
         if (notatxt.size() < 1) {
					 return;
				 }
				 notatxt.resize(110);
		
					for (int i=0; i<selezioni.size(); i++) {
						DayCell fday = selezioni[i]->data(Qt::UserRole).value<DayCell>();
						fday.note.clear();
						
															fday.note.append(notatxt);
						                  CalendarItem *Cell = fday.on_Table();
													    Cell->setData(Qt::UserRole,fday);
													    setItem(fday.tr_line,fday.td_line,Cell);
						                  taco.MemoDay.insert(fday.fromUday(),fday);  /* insert or replace memo !!!! */
					}
	}
	
	clearSelection();
	taco.lastupdate = QDateTime::currentDateTime();
	
}








void Calendar::contextMenuEvent ( QContextMenuEvent * e )
{
	  DayCell aday;
	  
	
	  QMenu *TContext = new QMenu();
	  QMenu *Tanni = new QMenu(tr("Anno %1").arg(ActiveYear));
	
	   for (int Years = MinY; Years <= MaxY; ++Years) {
           
			    if (Years != ActiveYear) {
			    QAction *ope = new QAction(this);
					/////ope->setIcon(QIcon(QString::fromUtf8(":/img/kappfinder.png")));
					ope->setText(tr("Apri anno %1").arg(Years));
					ope->setData ( Years );
					connect(ope, SIGNAL(triggered()), this,  SLOT(SwapYear()));
						 Tanni->addAction(ope);
					}
		 }
		 
		TContext->addAction(Tanni->menuAction());
		 
		 
		 if ( HavingYear( ActiveYear + 1 )) {
		 
		      QAction *openext = new QAction(this);
					/////ope->setIcon(QIcon(QString::fromUtf8(":/img/kappfinder.png")));
					openext->setText(tr("Prossimo Anno >>"));
					openext->setData ( ActiveYear + 1 );
					connect(openext, SIGNAL(triggered()), this,  SLOT(SwapYear()));
		      TContext->addAction(openext);
		 }
		 if ( HavingYear( ActiveYear - 1 )) {
		 
		      QAction *openprev = new QAction(this);
					/////ope->setIcon(QIcon(QString::fromUtf8(":/img/kappfinder.png")));
					openprev->setText(tr("Anno precedente <<"));
					openprev->setData ( ActiveYear - 1 );
					connect(openprev, SIGNAL(triggered()), this,  SLOT(SwapYear()));
		      TContext->addAction(openprev);
		 }
		 
		 
	  /* reservation modus    0= libero / 1= prenotato / 2= prenotato provvisorio / 3= riservato / 10 = chiuso / */
	  QAction *open0 = new QAction(tr("Rendi libero"),this);
    open0->setStatusTip(tr("Rendi libero"));
	  open0->setData(0);
    open0->setIcon ( aday.createColorToolButtonIcon(0) );
    connect(open0, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
		QAction *open1 = new QAction(tr("Prenotato"),this);
    open1->setStatusTip(tr("Prenotato"));
	  open1->setData(1);
	  open1->setIcon ( aday.createColorToolButtonIcon(1) );
    connect(open1, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
	  QAction *open2 = new QAction(tr("Provvisoriamente Riservato"),this);
    open2->setStatusTip(tr("Provvisoriamente Riservato"));
	  open2->setData(2);
	  open2->setIcon ( aday.createColorToolButtonIcon(2) );
    connect(open2, SIGNAL(triggered()), this,  SLOT(Riservati()));
	
		QAction *open3 = new QAction(tr("Periodo Occupato"),this);
    open3->setStatusTip(tr("Periodo Occupato"));
	  open3->setData(3);
		open3->setIcon ( aday.createColorToolButtonIcon(3) );
    connect(open3, SIGNAL(triggered()), this,  SLOT(Riservati()));
		
		QAction *open10 = new QAction(tr("Periodo Chiuso"),this);
    open10->setStatusTip(tr("Periodo Chiuso"));
	  open10->setData(10);
		open10->setIcon ( aday.createColorToolButtonIcon(10) );
    connect(open10, SIGNAL(triggered()), this,  SLOT(Riservati()));
		
		TContext->addAction(open0);
	  TContext->addAction(open1);
		TContext->addAction(open2);
		TContext->addAction(open3);
		TContext->addAction(open10);
		TContext->addSeparator ();
    TContext->addAction(tr( "Esporta come file" ), this , SLOT( ExportAsFile() ) );
		TContext->addAction(tr( "Importa da file" ), this , SLOT( ImportFromFile() ) );
		
		TContext->addSeparator ();
		TContext->addAction(tr( "Esporta html" ), this , SLOT( ExportFileHtml() ) );
		TContext->addAction(tr( "Esporta xml" ), this , SLOT( ExportFileXml() ) );
		TContext->addAction(tr( "Esporta come immagine" ), this , SLOT( ExportasImage() ) );
		
		
		TContext->addSeparator ();
		
		TContext->addAction(tr( "Inerisci una nota..." ), this , SLOT( Notaday() ) );
		
    TContext->exec(QCursor::pos());
		
		
    open0->deleteLater();
		open1->deleteLater();
		open2->deleteLater();
		open3->deleteLater();
		open10->deleteLater();
    TContext->deleteLater();
    delete TContext;
}

void Calendar::ImportFromFile()
{
	QString fixfile = QFileDialog::getOpenFileName(this, tr("Importa - Apri file"),
	                          QCoreApplication::applicationDirPath(),
	                                         "HouseCalendar_file (*.hcal)" );
    if (!fixfile.isEmpty()) {
			  QString inside;
			  QFile file(fixfile); 
								if (file.exists()) {
														if (file.open(QFile::ReadOnly | QFile::Text)) {
																inside = QString::fromUtf8(file.readAll());
															  file.close();
														}
								}
			
        TableCalendar ExternCalendar = openCalendar(inside);
			  taco.owner = ExternCalendar.owner;
				taco.data = ExternCalendar.data;
				taco.web = ExternCalendar.web;
				taco.lastupdate = ExternCalendar.lastupdate;
				taco.MemoDay.clear();
				taco.MemoDay = ExternCalendar.Works();
								
								PlayYear(ActiveYear);  ///////////  Launch years 
			
		}
	
}

void  Calendar::Import( const QString dat )
{
	      TableCalendar ExternCalendar = openCalendar(dat);
			  taco.owner = ExternCalendar.owner;
				taco.data = ExternCalendar.data;
				taco.web = ExternCalendar.web;
				taco.lastupdate = ExternCalendar.lastupdate;
				taco.MemoDay.clear();
				taco.MemoDay = ExternCalendar.Works();
				PlayYear(ActiveYear);  ///////////  Launch years 
	
}

QString Calendar::Export()
{
	int bigs = taco.MemoDay.size();
	
	if (bigs < 1) {
	QMessageBox::warning(0, tr("Error Calendar!"),tr("No item found, Select date to reserve..."));
	return QString();
	}
	
	taco.Html_build();
	
	QString dati = saveCalendar(taco);
	return dati;
}


void Calendar::ExportAsFile()
{
	int bigs = taco.MemoDay.size();
	
	if (bigs < 1) {
	QMessageBox::warning(0, tr("Error Calendar!"),tr("No item found, Select date to reserve..."));
	return;
	}
	QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("HouseCalendar_file (*.hcal)"));
	
	if (!fileName.isEmpty() ) {
		    if (!fileName.endsWith(".hcal")) {
            fileName.append(".hcal");
        } 
				const QString dati = saveCalendar(taco);
				QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << dati;
        f.close();
					
					
					
					
        }
	}
}




void Calendar::ExportasImage()
{
		QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("Image file (*.png)"));
	
	   	if (!fileName.isEmpty() ) {
		    if (!fileName.endsWith(".png")) {
            fileName.append(".png");
        } 
			
				QPixmap PicsDocument = taco.image_year(ActiveYear);
				PicsDocument.save(fileName,"PNG",42);
				OpenDe( QUrl(fileName) );
	   }
	
}


void Calendar::ExportFileHtml()
{
		QString htmldata = taco.html_year(ActiveYear);
	  //////QString htmldata = taco.Html_build();
	
		QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("Html file (*.html)"));
	
	   	if (!fileName.isEmpty() ) {
		    if (!fileName.endsWith(".html")) {
            fileName.append(".html");
        } 
				/////////const QString dati = doc->toHtml("utf-8");
				QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << htmldata;
        f.close();
        }
				
				OpenDe( QUrl(fileName) );
	}
	
}


void Calendar::ExportFileXml()
{
		/////QString htmldata = taco.html_year(ActiveYear);
	  QString htmldata = taco.Html_build();
	
		QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("XML file (*.xml)"));
	
	   	if (!fileName.isEmpty() ) {
		    if (!fileName.endsWith(".xml")) {
            fileName.append(".xml");
        } 
				/////////const QString dati = doc->toHtml("utf-8");
				QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << htmldata;
        f.close();
        }
	}
	
}




CalendarItem::CalendarItem( const QDate d )
    : QTableWidgetItem() 
{
  day = d;
	setText(QString("%1").arg(d.day()) ); 
	setSizeHint(QSize(10,10));
}

CalendarItem::CalendarItem(const QString &text)
    : QTableWidgetItem(text) 
{
 
}







/*






 QSize DateDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
 {
     if (qVariantCanConvert<DayCell>(index.data(Qt::UserRole))) {
         DayCell dat = qVariantValue<DayCell>(index.data(Qt::UserRole));
         return dat.sizeHint();
     } else {
         return QItemDelegate::sizeHint(option, index);
     }
 }

 
void DateDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
 {
	        drawBackground(painter,option,index);
	 
     if (qVariantCanConvert<DayCell>(index.data(Qt::UserRole))) {
            DayCell dat = qVariantValue<DayCell>(index.data(Qt::UserRole));
         
     } else {
         QItemDelegate::paint(painter, option, index);
     }
		 
		 
}
 

void DateDelegate::drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	
			
			  if (qVariantCanConvert<DayCell>(index.data(Qt::UserRole))) {
            DayCell dat = qVariantValue<DayCell>(index.data(Qt::UserRole));
					
					    if (dat.dax.dayOfWeek() == 7 && dat.modus !=0 ) {
							painter->fillRect(option.rect,QBrush(QColor("#e5e5e5"),Qt::BDiagPattern));
							} else {
							painter->fillRect(option.rect,dat.BG(dat.modus));
							painter->drawPixmap (5,5,5,5,dat.NoteIcon());
							}
							painter->save();
							painter->restore();
					
				} else {
					 QItemDelegate::drawBackground(painter, option, index);
				}
   
}





*/





